package com.cs543.j.client.cloudService.filesystem;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class Entry {

	public static final char DIRECTORY_DELIMITER = '/';
	
	public static final String JSON_OBJECT_NAME = "name";
	public static final String JSON_OBJECT_IS_DIRECTORY = "isDirectory";
	public static final String JSON_OBJECT_IS_FILE = "isFile";

	private String name;
	private Entry parent;

	public Entry(String name, Entry parent) {
		super();
		this.name = name;
		this.parent = parent;
	}
	
	public Entry(JSONObject jsonObject, Entry parent)
	{
		try {
			this.name = (String) jsonObject.get(JSON_OBJECT_NAME);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		this.parent = parent;
	}

	public String getName() {
		return name;
	}

	public Entry getParent() {
		return parent;
	}

	public abstract boolean isDirectory();

	public abstract boolean isFile();

	public boolean isRootDirectory() {
		return this.name == null && this.parent == null && this.isDirectory();
	}

	public String getPath() {
		if (this.isRootDirectory()) {
			return "" + DIRECTORY_DELIMITER;
		} else {
			if (this.parent.isRootDirectory())
				return this.parent.getPath() + this.name;
			else
				return this.parent.getPath() + DIRECTORY_DELIMITER + this.name;
		}
	}

	@Override
	public String toString() {
		return this.getPath();
	}

	public JSONObject toJSONObject()
	{
		JSONObject object = new JSONObject();

		try {
			object.put(JSON_OBJECT_IS_DIRECTORY, this.isDirectory());
			object.put(JSON_OBJECT_IS_FILE, this.isDirectory());
			object.put(JSON_OBJECT_NAME , this.name );
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		return object;
	}
	
	public static Entry getInstanceFromJSON(JSONObject jsonObject, Entry parent)
	{
		String name;
		try {
			name = (String) jsonObject.get(JSON_OBJECT_NAME);
			Boolean isDirectory = (Boolean) jsonObject.get(JSON_OBJECT_IS_DIRECTORY);
			Boolean isFile = (Boolean) jsonObject.get(JSON_OBJECT_IS_FILE);
			
			if(isDirectory && !isFile)
			{
				return new Directory(name, parent);
			}
			else if(!isDirectory && isFile)
			{
				return new File(name, parent);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return null;
	}
	
	public static JSONObject nameToJSONObject(String name, boolean isDirectory)
	{
		JSONObject entry = new JSONObject();
		try {
			entry.put("name", name);
			if (isDirectory) {
				entry.put("isDirectory", true);
				entry.put("isFile", false);
			} else {
				entry.put("isDirectory", false);
				entry.put("isFile", true);
			}
			
			return entry;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
		
}
